package de.mmis.helferlein.demo;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import de.mmis.core.base.DeserializableAnnotations.ConstructorDeserializable;
import de.mmis.core.base.DeserializableAnnotations.DeserializationConstructor;
import de.mmis.core.base.MethodDescriptor.P;
import de.mmis.core.base.event.AbstractObservable;
import de.mmis.core.base.event.Event;
import de.mmis.core.publishsubscribe.PublishSubscribe;
import de.mmis.core.publishsubscribe.PublishSubscribeImpl;
import de.mmis.core.publishsubscribe.PublishSubscribe.PublishSubscribeException;

/* GenericPublisher arguments:
 --gui
 --object "IntProd" "($java-object (de.mmis.applications.simpleExamples.publishsubscribe.IntProducer 1500))"
 --pubsub
 --object "FloatProd" "($java-object (de.mmis.applications.simpleExamples.publishsubscribe.FloatProducer 2500))"
 --pubsub
 */
public class IntProducer extends AbstractObservable<IntProducer.IntEvent> {

	@ConstructorDeserializable(typeIdentifier = "int-event")
	public static class IntEvent implements Event {
		private final int number;

		@DeserializationConstructor
		public IntEvent(@P("Int") int n) {
			number = n;
		}

		public int getInt() {
			return number;
		}

		@Override
		public String toString() {
			return "number: " + number;
		}
	}

	private int n = 0;

	public IntProducer(long period) {
		Timer timer = new Timer(true);
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				fireEvent(new IntEvent(n++));
			}
		}, 1000, period);
	}

	public void resetN() {
		n = 0;
	}

	public int getInt() {
		return n;
	}

	public static void main(String[] args) throws PublishSubscribeException,
			IOException {
		IntProducer p1 = new IntProducer(1500);
		FloatProducer p2 = new FloatProducer(2500);
		PublishSubscribe ps = PublishSubscribeImpl.getInstance();

		ps.addObservable(p1, "IntProd");
		ps.addObservable(p2, "FloatProd");

		System.in.read();

		ps.removeObservable(p1);
		ps.removeObservable(p2);
	}

}
